<?php

namespace App\Http\Controllers\Admin\Api;

use App\Exceptions\LogicException;
use App\Http\Controllers\Controller;
use App\Models\Api\Apis;
use App\Models\Env\Host;
use App\Models\Env\HostEnv;
use App\Models\Module\ProductModule;
use App\Utils\QueryUtil;
use App\Utils\ResUtil;
use App\Models\Adminer\Admins;


class ApisController extends Controller
{
    public function list()
    {
        $request = request()->all();
        $query = Apis::where(function($query) use($request) {
            QueryUtil::selectBuild($query, $request, [
                ['cate_id', '='],
                ['project_id', '='],
                ['product_id', '='],
                ['enable', '='],
                ['f_module_id', '='],
                ['s_module_id', '='],
                ['host_id', '='],
                ['method_type', '='],
                ['name', 'like', 'name'],
                ['api', 'like', 'api'],
                ['remark', 'like', 'remark'],
                ['note', 'like', 'note'],
                ['tags', 'like', 'tags'],
                ['created_adminer', 'like', 'created_adminer'],
                ['updated_adminer', 'like', 'updated_adminer'],
                ['id', '=']
            ]);
        });

        $total = $query->count();
        $models = QueryUtil::queryList($query, 'sort');
        $list = [];
        foreach($models as $i => $v) {
            $list[$i] = $v?->label()?->Explode()?->toArray();
        }
        $hasMore = QueryUtil::hasMore(sizeof($list));
        $method_type_maps = Apis::$method_type_maps;
        return $this->ok(compact('list', 'total', 'hasMore', 'method_type_maps'));
    }

    public function edit()
    {
        $data = request()->all();
        $rule = [
            'id' => '',
            's_module_id' => 'required',
            'method_type' =>  'required',
            'name' => 'string|required',
            'api' => 'string|required',
            'remark' => '',
            'note' => '',
            'tags' => '',
            'sort' => '',
            'enable' => '',
        ];
        $validator = validatorService()->checkValidator($rule, $data, Apis::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }

        if($data['id'] ?? '') {
            $Apis = Apis::find($data['id']);
            if(!$Apis) {
                throw new LogicException(ResUtil::NOT_DATA);
            }
        } else {
            $Apis = new Apis;
            $Apis->enable = 1;
            $Apis->created_adminer = Admins::getInfoById($this->authAdmin()->id);
        }

        $s_module = ProductModule::where('level', 2)->find($data['s_module_id']);
        if(!$s_module) {
            throw new LogicException('产品子模块不存在');
        }

        // 验证域名合法性
        if(strpos("_".$data['api'],'{{') == false || strpos("_".$data['api'],'}}') == false){
            if(strpos("_".$data['api'],'http') == false) {
                throw new LogicException('请用{{xl_admin_utl}}或者https或者http方式来补充接口域名');
            }
        } else {
            if(strpos("_".$data['api'],'{{') == true && strpos("_".$data['api'],'}}') == true){
                $host = explode("}}", substr($data['api'],2,strlen($data['api'])));
                if(empty($host[0])) {
                    throw new LogicException('请用{{xl_admin_utl}}或者https或者http方式来补充接口域名');
                } else {
                    $ex = HostEnv::getByName($host[0]);
                    if(!$ex) {
                        throw new LogicException("{$host[0]}环境标识不存在,请添加环境标识");
                    }
                    if(!$host_url = Host::where('host_env_id', $ex->id)->where('enable', 1)->first()) {
                        throw new LogicException("{$host[0]}环境标识下没有可用的域名,请添加");
                    }
                }
            } else {
                throw new LogicException('请用{{xl_admin_utl}}或者https或者http方式来补充接口域名');
            }
        }

        $tags = '';
        if(!empty($data['tags']) && is_array($data['tags']??'')) {
            $tags = implode(',', $data['tags']);
        }

        $Apis->fill([
            'cate_id' => $s_module->cate_id,
            'project_id' => $s_module->project_id,
            'product_id' => $s_module->product_id,
            'f_module_id' => $s_module->p_id,
            's_module_id' => $s_module->id,
            'host_id' => $ex->id ?? 0,
            'method_type' => $data['method_type'],
            'name' => $data['name'],
            'api' => $data['api'],
            'remark' => $data['remark'] ?? '',
            'note' => $data['note'] ?? '',
            'tags' => $tags,
            'sort' => $data['sort'] ?? 1,
            'enable' => $data['enable'] ?? 1,
            'updated_adminer' => Admins::getInfoById($this->authAdmin()->id),
        ]);
        $Apis->save();
        return $this->ok();
    }

    public function enable()
    {
        $data = request()->all();
        $rule = [
            'id' => 'integer|required',
            'enable' => 'integer|required|in:1,0',
        ];
        $validator = validatorService()->checkValidator($rule, $data, Apis::$fillables);
        if ($validator['code'] != 200) {
            throw new LogicException($validator['data']);
        }
        $Apis = Apis::find($data['id']);
        if(!$Apis) {
            throw new LogicException(ResUtil::NOT_DATA);
        }

        $Apis->enable = $data['enable'];
        $Apis->save();
        return $this->ok();
    }

    public function allApis()
    {
        $list = Apis::select('id', 'name')->get();
        return $this->ok(compact('list'));
    }
}
